// pages/foodDetail/food.js
import { getFoodById, addDietRecord ,addFoodEntry,addPlanFood } from '../../http/api';
import eventBus from '../../utils/eventBus';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    food: null, // 当前食物的详细信息
    nutrients: [], // 营养成分列表
    isPopupVisible: false, // 弹出框是否可见
    popupAnimation: null,
    meals: [
      { id: '1', name: '早餐' },
      { id: '2', name: '午餐' },
      { id: '3', name: '晚餐' },
      { id: '4', name: '加餐' }
    ],
    userId: null,
    isEditMode:false
  },

  /**
  * 生命周期函数--监听页面加载
  */
  onLoad(options) {   
    // 尝试获取全局用户ID
    this.checkUserStatus();
    const foodId = options.id;    
    const action = options.action
    if (foodId) {
      this.getFoodDetail(foodId);
    } else {
      wx.showToast({
        title: '未找到食物 ID',
        icon: 'none'
      });
    }
    if(action) {
      this.setData({ isEditMode:action=='edit'?true:false })
    }
  },
  onUnload: function () {
    // 页面卸载时移除事件监听，防止内存泄漏
    eventBus.off('foodAdded');
  },  
  /**
  * 根据食物 ID 获取食物详情
  * @param {number} foodId - 食物 ID
  */
  getFoodDetail: function (foodId) {
    wx.showLoading({
      title: '加载中...',
    });    
    // 调用后端 API
    getFoodById(foodId)
      .then((res) => {
        wx.hideLoading();        
        if (res.success && res.data) {
          const food = res.data;
          const imageBaseUrl = 'https://wechatobject-1355794559.cos.ap-guangzhou.myqcloud.com/food/'; // 图片基础路径
          const imageExtension = '.png'; // 图片扩展名
          food.image = `${imageBaseUrl}${food.image}${imageExtension}`;
          // 更新页面数据
          this.setData({
            food: food,
            nutrients: [
              { type: 'protein', name: '蛋白质', value: `${food.protein || 0}g` },
              { type: 'carbs', name: '碳水化合物', value: `${food.carbohydrate || 0}g` },
              { type: 'fat', name: '脂肪', value: `${food.fat || 0}g` },
              { type: 'vitaminC', name: '维生素C', value: `${food.vitaminC || 0}mg` },
              { type: 'calories', name: '热量', value: `${food.calories || 0}kcal` },
              { type: 'minerals', name: '矿物质', value: food.minerals || 'N/A' }
            ]
          });
        } else {
          wx.showToast({
            title: '获取食物详情失败',
            icon: 'none'
          });
        }
      })
      .catch((error) => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        console.error('请求失败:', error);
      });
  },

  /**
   * 检查用户登陆状态
   */
  checkUserStatus() {    
    const app = getApp();
    if (app.globalData.userId) {
      this.setData({ userId: app.globalData.userId });
    } else {
      // 如果没有登录，可以提示用户登录
      wx.showModal({
        title: '提示',
        content: '请先登录',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({ url: '/pages/user/user' });
          }
        }
      });
    }
  },

  // 显示弹出框
  showMealSelectionPopup: function() {
    const animation = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease'
    });

    // 定义动画效果
    animation.opacity(1).scale(1, 1).step();

    this.setData({
      isPopupVisible: true,
      popupAnimation: animation.export()
    });
  },

  // 隐藏弹出框
  hideMealSelectionPopup: function() {
    const animation = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease'
    });

    // 定义动画效果
    animation.opacity(0).scale(0.8, 0.8).step();

    this.setData({
      popupAnimation: animation.export()
    });

    setTimeout(() => {
      this.setData({ isPopupVisible: false });
    }, 300); // 动画结束后隐藏弹窗
  },

  /**
   * 添加食物到指定餐次
   * @param {Object} e - 事件对象
   */
  addFoodToMeal: function(e) {    
    const mealId = e.currentTarget.dataset.meal; // 获取选择的餐次 ID
    const food = this.data.food;
  
    // 弹出输入框，让用户输入克数
    wx.showModal({
      title: '请输入克数',
      content: '默认值为 100 克',
      editable: true,
      success: (res) => {
        if (res.confirm) {
          let grams = parseFloat(res.content) || 100;          
          if (this.data.isEditMode) {
            addPlanFood(
              wx.getStorageSync('userInfo').userId, 
              food.id, 
              mealId, 
              grams)
              .then((res) => {
                if (res.success) {
                  wx.showToast({ title: '添加成功' });  
                  eventBus.emit('foodAdded', { 
                    mealType: mealId,
                    planId: res.data.id,
                    action:'edit',
                    food,
                    grams                  
                  });
                } else {
                  wx.showToast({ title: '添加失败', icon: 'none' });
                }                                
              })          
          } else {
            addFoodEntry({
              foodId: food.id,
              grams: grams            
            })
            .then(entryRes => {                 
              return addDietRecord({
                userId: wx.getStorageSync('userInfo').userId,
                mealType: mealId, // 确保使用正确的mealId变量
                foodEntryId: entryRes.id
              });
            }).then((res) => {              
              wx.showToast({ title: '添加成功' });
              // 发送事件通知餐次页面刷新
              eventBus.emit('foodAdded', { 
                foodEntryId:res.foodEntryId,
                recordId: res.recordId,
                mealType: mealId,
                action:'query',
                food,
                grams
              });
            })
          }
        }                    
      }
    });
  },
  
  // 获取餐次名称
  getMealName: function(mealId) {
    const meal = this.data.meals.find(m => m.id === mealId);
    return meal ? meal.name : '';
  },
  // 阻止触摸移动（防止滚动穿透）
  preventTouchMove: function() {},
  navigateBack: function () {
    wx.navigateBack({
      delta: 1 // 返回的页面数，如果 delta 大于现有页面数，则返回到首页。
    });
  },
  // 或者监听全局数据变化
  onShow() {
    const userId = wx.getStorageSync('userInfo').userId;
    if (userId) {
      this.setData({ userId: userId });
    } else {
      console.log('用户未登录');
    }
  }
})